package com.crowntit.domain.trade.service.lock.filter;

import com.crowntit.domain.trade.adapter.repository.ITradeRepository;
import com.crowntit.domain.trade.model.entity.GroupBuyActivityEntity;
import com.crowntit.domain.trade.model.entity.TradeLockRuleBackEntity;
import com.crowntit.domain.trade.model.entity.TradeLockRuleCommandEntity;
import com.crowntit.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import com.crowntit.types.design.framework.link.model2.handler.ILogicHandler;
import com.crowntit.types.enums.ResponseCode;
import com.crowntit.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class TeamStockOccupyRuleFilter implements ILogicHandler<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleBackEntity> {

    @Resource
    private ITradeRepository repository;

    @Override
    public TradeLockRuleBackEntity apply(TradeLockRuleCommandEntity requestParam, TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("交易规则过滤-组队库存校验 {} activityId: {}", requestParam.getUserId(), requestParam.getActivityId());

        String teamId = requestParam.getTeamId();
        if (StringUtils.isBlank(teamId)){
            return TradeLockRuleBackEntity.builder()
                    .userTakeLimitCount(dynamicContext.getUserTakeLimitCount())
                    .build();
        }

        GroupBuyActivityEntity groupBuyActivity = dynamicContext.getGroupBuyActivity();
        Integer target = groupBuyActivity.getTarget();
        Integer validTime = groupBuyActivity.getValidTime();
        String teamStockKey = dynamicContext.generateTeamStockKey(teamId);
        String recoveryTeamStockKey = dynamicContext.generateRecoveryTeamStockKey(teamId);

        boolean status = repository.occupyTeamStockKey(teamStockKey, recoveryTeamStockKey, target, validTime);
        if (!status){
            log.warn("交易规则过滤-组队库存校验{} activityId:{} 抢占失败:{}", requestParam.getUserId(), requestParam.getActivityId(), teamStockKey);
            throw new AppException(ResponseCode.E0009.getCode(), ResponseCode.E0009.getInfo());
        }

        return TradeLockRuleBackEntity.builder()
                .userTakeLimitCount(dynamicContext.getUserTakeLimitCount())
                .recoveryTeamStockKey(recoveryTeamStockKey)
                .build();
    }
}
